package cometd.test.components;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;

import cometd.test.ChatServlet;

public abstract class LongRunningConnectionNotifier extends Panel
{
	long connectionId;
	public LongRunningConnectionNotifier( String id, final String... notifierIDs) 
	{
		super( id );
		final AbstractDefaultAjaxBehavior ajax = new AbstractDefaultAjaxBehavior(){
			@Override
			protected void respond(AjaxRequestTarget target) 
			{
				String n = getRequest().getParameter("channels");
				LongRunningConnectionNotifier.this.onNotify( Arrays.asList( n.split("_") ), target );
			}
			
		};
		add( ajax );

		connectionId = ChatServlet.getNextId();

		
		add( new WebMarkupContainer( "script"){
			@Override
			protected void onComponentTagBody(MarkupStream markupStream,
					ComponentTag openTag) {
				String n="";
				for( String id : notifierIDs )n+="_"+id;
				n=n.substring(1);
				getResponse().write( "var channels='"+n+"';" );
				getResponse().write( "var connectionId="+connectionId+";" );
				getResponse().write( "var callbackUrl='"+ajax.getCallbackUrl(false)+"';" );
				super.onComponentTagBody(markupStream, openTag);
			}
		});
	}
	
	public abstract void onNotify( List<String> n, AjaxRequestTarget target );

	public void notify(String channel) 
	{
		ChatServlet.notify(connectionId, channel);
	} 
}
